package com.story.aistory.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.story.aistory.domain.po.ReadRecord;
import com.story.aistory.domain.po.Users;
import com.story.aistory.mapper.ReadRecordMapper;
import com.story.aistory.service.IReadRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.story.aistory.utils.AppThreadLocalUtil;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hui
 * @since 2025-03-12
 */
@Service
public class ReadRecordServiceImpl extends ServiceImpl<ReadRecordMapper, ReadRecord> implements IReadRecordService {

    @Override
    public void add(Integer storyId) {
        if (AppThreadLocalUtil.getUser() == null) {
            throw new RuntimeException("User not login");
        }
        Users user = AppThreadLocalUtil.getUser();
        ReadRecord readRecord = new ReadRecord();
        readRecord.setUserId(user.getId());
        readRecord.setStoryId(storyId);
        this.save(readRecord);
    }

    @Override
    public void delete(Integer storyId) {
        if (AppThreadLocalUtil.getUser() == null) {
            throw new RuntimeException("User not login");
        }
        Users user = AppThreadLocalUtil.getUser();
        remove(new QueryWrapper<ReadRecord>().eq("user_id", user.getId()).eq("story_id", storyId));
    }

    @Override
    public void deleteAll() {
        if (AppThreadLocalUtil.getUser() == null) {
            throw new RuntimeException("User not login");
        }
        Users user = AppThreadLocalUtil.getUser();
        remove(new QueryWrapper<ReadRecord>().eq("user_id", user.getId()));
    }

    @Override
    public List<ReadRecord> getAll() {
        if (AppThreadLocalUtil.getUser() == null) {
            throw new RuntimeException("User not login");
        }
        Users user = AppThreadLocalUtil.getUser();
        QueryWrapper<ReadRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", user.getId());
        queryWrapper.orderByDesc("create_time");
        return this.list(queryWrapper);
    }
}
